package com.jright.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.jright.po.Admin;
import com.jright.po.Student;
import com.jright.po.Teacher;
import com.jright.service.AdminService;
import com.jright.service.StudentService;
import com.jright.service.TeacherService;

import net.sf.json.JSONObject;

@Controller
public class MyController{

	@Autowired
	private StudentService studentService;
	@Autowired
	private TeacherService teacherService;
	@Autowired
	private AdminService adminService;
	
	@PostMapping("/login")
	public String login(String no, String password, String identity, HttpServletRequest request,HttpSession session) {
		String url = null;
		if(identity.equals("student")) {
			Student student = studentService.findStudent(no, password);
			if(student == null) {
				request.setAttribute("msg", "账号不存在或者密码错误!");
				url = "forward:login.jsp";
			}else {
				session.setAttribute("student", student);
				url = "redirect:student/toIndex.do";
			}
		}else if(identity.equals("admin")) {
			Admin admin = adminService.findAdmin(no, password);
			if(admin == null) {
				request.setAttribute("msg", "账号不存在或者密码错误!");
				url = "forward:login.jsp";
			}else {
				session.setAttribute("admin", admin);
				url = "redirect:admin/toIndex.do";
			}
		}else {
			Teacher teacher = teacherService.findTeacher(no, password, identity);
			if(teacher == null) {
				request.setAttribute("msg", "账号不存在或者密码错误!");
				url = "forward:login.jsp";
			}else {
				if(identity.equals("teacher")) {
					session.setAttribute("teacher", teacher);
					url = "redirect:teacher/toIndex.do";
				}else {
					session.setAttribute("jury", teacher);
					url = "redirect:jury/toIndex.do";
				}
			}
		}
		return url;
	}
	
	/**
	 * 执行文件上传
	 */
	@RequestMapping(value = "/uploadFile", method = { RequestMethod.POST })
	@ResponseBody
	public JSONObject uploadHeadImage(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpSession session, InputStream stream)
			throws IOException {
		Student student = (Student) session.getAttribute("student");
		JSONObject json = new JSONObject();
		if(student.getChoose_topic() != null && student.getChoose_topic().getStatus().equals("审核通过")) {
			Assert.notNull(file, "上传文件不能为空");
			String filename = file.getOriginalFilename();
			String dirPath =  request.getServletContext().getRealPath("/upload/");
			File filePath = new File(dirPath);
			if (!filePath.exists()) {
				filePath.mkdirs();
			}
			//System.currentTimeMillis()根据系统时间产生随机数，保证上传的图片名字不一样
			String newFilename = System.currentTimeMillis()+"-"+filename;
			System.out.println(dirPath + newFilename);
			file.transferTo(new File(dirPath + newFilename));
			json.put("msg","上传成功");
			json.put("code",0);
			json.put("filePath", dirPath + newFilename);
			json.put("fileName", newFilename);
		}else {
			json.put("code",0);
			json.put("msg","选题未通过后者尚未选题，不能上传论文");
		}
		return json;
	}
	@RequestMapping("/download")
	public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,
	                                           String filename) throws Exception{
	    // 指定要下载的文件所在路径
	    String path = request.getServletContext().getRealPath("/upload/");
	    // 创建该文件对象
	    File file = new File(path+File.separator+filename);
	    // 对文件名编码，防止中文文件乱码
	    filename = this.getFilename(request, filename);
	    // 设置响应头
	    HttpHeaders headers = new HttpHeaders();
	    // 通知浏览器以下载的方式打开文件
	    headers.setContentDispositionFormData("attachment", filename);
	    // 定义以流的形式下载返回文件数据
	    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
	    // 使用Sring MVC框架的ResponseEntity对象封装返回下载数据
	   return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
	                                           headers,HttpStatus.OK);
	}
	/**
	 * 根据浏览器的不同进行编码设置，返回编码后的文件名
	 */
	public String getFilename(HttpServletRequest request,
	                                            String filename) throws Exception { 
	    // IE不同版本User-Agent中出现的关键词
	    String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};  
	    // 获取请求头代理信息
	    String userAgent = request.getHeader("User-Agent");  
	    for (String keyWord : IEBrowserKeyWords) { 
	         if (userAgent.contains(keyWord)) { 
	              //IE内核浏览器，统一为UTF-8编码显示
	              return URLEncoder.encode(filename, "UTF-8");
	         }
	    }  
	    //火狐等其它浏览器统一为ISO-8859-1编码显示
	    return new String(filename.getBytes("UTF-8"), "ISO-8859-1");  
	}  
	
	
}
